#include "TCPServer.h"
#include "Foundation.h"
#include "ErrorCode.h"



CTCPServer::CTCPServer()
{
}


CTCPServer::~CTCPServer()
{
}


int CTCPServer::StartServer(const std::string strIP, const int nPort, const int nMaxListen)
{
    unsigned long lIp;
    if("-1" == strIP)
    {
        lIp = htonl(INADDR_ANY);
    }
    else
    {
        int nTemp = CFoundation::IPv4ToLong(strIP);
        if(-1 == nTemp)
        {
            return NETDEBUG_IP_ERR;
        }
        lIp = (unsigned long)nTemp;
    }
    if(0 >= nPort || 65535 <= nPort)
    {
        return NETDEBUG_PORT_ERR;
    }

    m_nSocket_fd = SOCKET_CREATE(AF_INET, SOCK_STREAM, 0);
    if(SOCKET_CHECK(m_nSocket_fd))
    {//Create socket error
        return NETDEBUG_SOCKET_ERR;
    }

    m_addrHost.sin_family = AF_INET;
    m_addrHost.sin_port = htons(nPort);
	m_addrHost.sin_addr.s_addr = lIp;

	int nRet;
    if(0 > (nRet = SOCKET_BING(m_nSocket_fd, (struct sockaddr *)&(m_addrHost), sizeof(m_addrHost)) ))
    {
        return NETDEBUG_BIND_ERR;
    }

    if(0 > SOCKET_LISTEN(m_nSocket_fd, nMaxListen))
    {
        return NETDEBUG_LISTEN_ERR;
    }
	return NETDEBUG_SUCCESS;
}


CSocket* CTCPServer::Accept()
{   
    SOCKET nSocket;
    struct sockaddr_in addrHost;
	SOCKLEN_T socklen = sizeof(addrHost);
    nSocket = SOCKET_ACCEPT(m_nSocket_fd, (struct sockaddr *)&(addrHost), &socklen);

    if(0 >= nSocket )
    {
        return NULL;
    }
    else
    {
        CSocket *sockClient = CreateClientConnection(nSocket, addrHost);
        return sockClient;
    }
}